package com.kwok.mpgenerator.web.service.impl;

import com.kwok.mpgenerator.web.entity.User;
import com.kwok.mpgenerator.web.entity.dto.UserDto;
import com.kwok.mpgenerator.web.entity.query.UserQuery;
import com.kwok.mpgenerator.web.entity.form.UserForm;
import com.kwok.mpgenerator.web.mapper.UserMapper;
import com.kwok.mpgenerator.web.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

/**
* 用户表 服务实现类
* @author kwok
* @date 2023-12-28
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional(rollbackFor=Exception.class)
    public Long addUser(UserForm form){
        User user = new User();
        BeanUtils.copyProperties(form, user);
        int insert = userMapper.insert(user);
        return user.getId();
    }

    @Override
    public Page<UserDto> getPageList(@RequestBody UserQuery query){
        Page<User> page = new Page<>(query.getPageNum(), query.getPageSize());
        LambdaQueryWrapper<User> queryWrapper = UserQuery.getQueryWrapper(query);
        IPage<User> userPage = userMapper.selectPage(page, queryWrapper);
        Page<UserDto> userDtoPage = new Page<>();
        BeanUtils.copyProperties(userPage, userDtoPage);
        userDtoPage.setRecords(UserDto.toDtoList(userPage.getRecords()));
        return userDtoPage;
    }

    @Override
        @Transactional(rollbackFor=Exception.class)
        public Long updateUser(UserForm form){
        User user = new User();
        BeanUtils.copyProperties(form, user);
        int update = userMapper.updateById(user);
        return user.getId();
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public UserDto getUserById(Long id){
        User entity = userMapper.selectById(id);
        return UserDto.toDto(entity);
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public Integer removeUser(Long id){

        return userMapper.deleteById(id);
    }

}
